const { success, notFound, error } = require('../utils/response');
const productModel = require('../models/productModel');

const getAllProducts = async (req, res) => {
  try {
    const products = await productModel.getAllProducts();
    success(res, products);
  } catch (err) {
    error(res, err.message);
  }
};

const getProductsByCategory = async (req, res) => {
  try {
    const products = await productModel.getProductsByCategory(req.params.categoryId);
    success(res, products);
  } catch (err) {
    error(res, err.message);
  }
};

const getProductById = async (req, res) => {
  try {
    const product = await productModel.getProductById(req.params.id);
    if (!product) {
      return notFound(res, 'Product not found');
    }
    success(res, product);
  } catch (err) {
    error(res, err.message);
  }
};

const searchProducts = async (req, res) => {
  try {
    const { keyword } = req.query;
    if (!keyword) {
      return badRequest(res, 'Please provide a search keyword');
    }
    const products = await productModel.searchProducts(keyword);
    success(res, products);
  } catch (err) {
    error(res, err.message);
  }
};

module.exports = {
  getAllProducts,
  getProductsByCategory,
  getProductById,
  searchProducts
};